from django.db import models
from django.utils.timezone import now


class Log(models.Model):
    user = models.CharField(verbose_name="操作者", max_length=255, null=True, blank=True)
    action = models.CharField(verbose_name="操作类型 CREATE/UPDATE/DELETE", max_length=50, null=True, blank=True)
    model_name = models.CharField(verbose_name="操作的哪张表", max_length=255, null=True, blank=True)
    object_id = models.CharField(verbose_name="被操作对象的id", max_length=255, null=True, blank=True)
    object_repr = models.CharField(verbose_name="被操作对象的表示", max_length=255, null=True, blank=True)
    url = models.CharField(verbose_name="当前访问的路径/接口", max_length=255, null=True, blank=True)
    browser = models.CharField(verbose_name="浏览器类型", max_length=255, null=True, blank=True)
    ip_address = models.GenericIPAddressField(verbose_name="IP地址", null=True, blank=True)
    status = models.CharField(verbose_name="http请求状态码 - (成功200/服务器错误500)", max_length=50)
    message = models.TextField(verbose_name="500的错误信息", null=True, blank=True)
    create_datetime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    def __str__(self):
        return f"[{self.create_datetime.strftime('%Y-%m-%d %H:%M:%S')}] {self.user} {self.status} {self.url} {self.object_id}"

    def json(self):
        return {
            "id": self.id,
            "user": self.user,
            "action": self.action,
            "model_name": self.model_name,
            "object_id": self.object_id,
            "object_repr": self.object_repr,
            "url": self.url,
            "browser": self.browser,
            "ip_address": self.ip_address,
            "status": self.status,
            "message": self.message,
            "create_datetime": self.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
        }
